package com.lungle.warmdiary.app.view;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.widget.MySwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.Scrollable;
import com.github.ksoichiro.android.observablescrollview.TouchInterceptionFrameLayout;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.content.db.DAOFactory;
import com.lungle.warmdiary.app.content.db.MediaAccountDAO;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.ActiveStatueRefreshEvent;
import com.lungle.warmdiary.app.model.event.ActiveTabHostEvent;
import com.lungle.warmdiary.app.model.event.CampaignStatueRefreshEvent;
import com.lungle.warmdiary.app.model.event.MediaChangeEvent;
import com.lungle.warmdiary.app.model.event.UserChangeEvent;
import com.lungle.warmdiary.app.model.response.MediaAccount;
import com.lungle.warmdiary.app.model.response.MediaAccountList;
import com.lungle.warmdiary.app.model.response.MediaChannel;
import com.lungle.warmdiary.app.model.response.MediaChannelList;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.service.push.JPushService;
import com.lungle.warmdiary.app.ui.tab.SlidingTabLayout;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.ShareHelperForPopWindows;
import com.lungle.warmdiary.app.utils.SimpleAnimation;
import com.lungle.warmdiary.app.utils.TDevice;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.utils.UpdateManager;
import com.lungle.warmdiary.app.view.active.ActiveTab;
import com.lungle.warmdiary.app.view.active.adapter.MediaSelectAdapter;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class MainActivity extends BaseActivity implements OnTabChangeListener, IMainTab,
        ObservableScrollViewCallbacks, MediaSelectAdapter.onAccountSelected {

    private static final String MAIN_SCREEN = "MainScreen";

    public static final String ACTION_KEY = "redirect_action";
    public static final String ACTION_KEY_STATUS = "active_status";

    public static final int ACTION_REDIRECT_DEFALULT = 0x00;
    public static final int ACTION_REDIRECT_MESSAGE = 0x10;
    public static final int ACTION_REDIRECT_ADD_MEDIA_ACCOUNT = 0x01;

    private FragmentTabHost mTabHost;
    private Toolbar mToolbarView;
    private ScrollState mLastScrollState;
    private LinearLayout mPagerWrapper;
    private View mErrorLayout;
    private TouchInterceptionFrameLayout mInterceptionLayout;
    private int mTabHeight;
    private PopupWindow mSelectPopup;
    private ImageView mIvArrow;
    private TextView mActionTitleView;
    private MediaSelectAdapter mAdapter;

    private int mSlop;
    private boolean mScrolled;
    private ListView mLvChannelContainer;
    private MediaChannelList mediaChannelList = new MediaChannelList();

    private MediaAccountDAO mediaAccountDAO;
    private long mLastExitTime;

    private static long last_media_account_update = 0L;

    private User mUser;
    private String UserName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        checkUpdate();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String mShareChannel = ShareHelperForPopWindows.obtainInstallList();
                AppContext.getInstance().setShare(mShareChannel);
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mUser = AppContext.getInstance().getLoginUser();
        if (mUser != null) {
            UserName = mUser.getUsername();
        }

        //dashboard 我-活动跳转
        int status = getIntent().getIntExtra(ACTION_KEY_STATUS, -1);
        //clean the intent
        getIntent().removeExtra(ACTION_KEY_STATUS);

        if (status > 0) {
            LogUtils.printLogD(status + "");
            mTabHost.setCurrentTab(1);
            if (status == ActiveTab.UNLIMITED.getIdx())
                notifyTabChange(0);
            else
                notifyTabChange(status);
        }
        MobclickAgent.onPageStart(MAIN_SCREEN);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(MAIN_SCREEN);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
//        if (mReceiver != null) unregisterReceiver(mReceiver);
        if (mediaAccountDAO != null) mediaAccountDAO.close();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }


    private void checkUpdate() {
        Handler handler = new Handler();
        handler.postDelayed(() -> new UpdateManager(MainActivity.this, false).checkUpdate(), 2000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);//must store the new intent unless getIntent() will return the old one
    }

    private void redirectTo() {
        Intent intent = getIntent();
        int redict = intent.getIntExtra(ACTION_KEY, ACTION_REDIRECT_DEFALULT);
        switch (redict) {
            case ACTION_REDIRECT_MESSAGE:
                if (AppContext.hasMediaAccount())
                    UIHelper.showMessage(this);
                break;
            case ACTION_REDIRECT_ADD_MEDIA_ACCOUNT:
                UIHelper.showMediaCenter(this);
                break;
        }

    }


    private void registerJPush() {
//        if (!AppContext.getInstance().isFristInitJPush()) {
        new JPushService(this).register("meida_tag", "media_alias");
//        }
    }


    @Override
    protected boolean hasBackButton() {
        return false;
    }


    @Override
    protected boolean isDefaultActionBar() {
        return true;
    }

    @Override
    protected int getActionBarCustomView() {
        return R.layout.actionbar_main;
    }

    @Override
    protected void initActionBar(Toolbar actionBar) {
        super.initActionBar(actionBar);
        mToolbarView = actionBar;
        mActionTitleView = (TextView) actionBar.findViewById(R.id.action_bar_title1);
        mIvArrow = (ImageView) actionBar.findViewById(R.id.iv_actionbar_indicator);
        mActionTitleView.setText("亲测");
        mIvArrow.setVisibility(View.GONE);
        mActionTitleView.setOnClickListener(v -> {
            if (mSelectPopup != null && mSelectPopup.isShowing()) {
                hideMediaAccountSelector();
            } else {
                showMediaAccountSelector(v);
            }
        });
    }


    private void hideMediaAccountSelector() {
        if (mSelectPopup != null && mSelectPopup.isShowing()) {
            mSelectPopup.dismiss();
        }
    }


    public void showMediaAccountSelector(View v) {
        if (!AppContext.hasMediaAccount()) return;
        loadMediaAccountList(1);
        if (mSelectPopup != null && !mSelectPopup.isShowing()) {
            SimpleAnimation.rotateArrow(mIvArrow, false);
            mSelectPopup.showAsDropDown(v, 0, 5);
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 0.4f;
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            getWindow().setAttributes(lp);
        }

    }


    //init active select
    public void createMediaAccountSelector() {
        if (mSelectPopup == null) {
            View layout = getLayoutInflater().inflate(R.layout.view_active_select, null);
            mLvChannelContainer = (ListView) layout.findViewById(R.id.lv_channel_container);
            layout.findViewById(R.id.btn_all_media).setOnClickListener(v -> {
                mSelectPopup.dismiss();
                MediaAccount mediaAccount = new MediaAccount();
                mediaAccount.setName("全部");
                mediaAccount.setId("0");
                notifyAccountSelected(mediaAccount);
            });

            mSelectPopup = new PopupWindow(layout, (int) TDevice.getScreenWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
//            mSelectPopup.setBackgroundDrawable(new BitmapDrawable());
            mSelectPopup.update();
            mSelectPopup.setFocusable(true);
            mSelectPopup.setOutsideTouchable(true);
            mSelectPopup.setOnDismissListener(() -> {
                SimpleAnimation.rotateArrow(mIvArrow, true);
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            });

            if (mAdapter == null) {
                mAdapter = new MediaSelectAdapter(MainActivity.this, MainActivity.this, mediaChannelList);
                mLvChannelContainer.setAdapter(mAdapter);
            }

            loadMediaAccountList(0);
        }
    }


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        redirectTo();
        registerJPush();
        AppContext.instance().initLoginInfo();
        createMediaAccountSelector();
        mPagerWrapper = (LinearLayout) findViewById(R.id.pager_wrapper);
//
//        if (AppContext.hasMediaAccount()) {//通知可以
//            notifyAccountChange("0");
//        }


        mTabHeight = 0;
        mPagerWrapper.setPadding(0, getActionBarSize() + mTabHeight, 0, 0);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        if (Build.VERSION.SDK_INT > 10) {
            mTabHost.getTabWidget().setShowDividers(0);
        }

        initTabs();

        mTabHost.setCurrentTab(0);
        mTabHost.setOnTabChangedListener(this);


        ViewConfiguration vc = ViewConfiguration.get(this);
        mSlop = vc.getScaledTouchSlop() / 2;
        mInterceptionLayout = (TouchInterceptionFrameLayout) findViewById(R.id.container);
//        mInterceptionLayout.setScrollInterceptionListener(mInterceptionListener);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
    }


    private void initTabs() {
        MainTab[] tabs = MainTab.values();
        final int size = tabs.length;
        for (int i = 0; i < size; i++) {
            MainTab mainTab = tabs[i];
            TabSpec tab = mTabHost.newTabSpec(getString(mainTab.getResName()));

            View indicator = inflateView(R.layout.v2_tab_indicator);
            ImageView icon = (ImageView) indicator.findViewById(R.id.tab_icon);
            icon.setImageResource(mainTab.getResIcon());
            TextView title = (TextView) indicator.findViewById(R.id.tab_titile);
            title.setText(getString(mainTab.getResName()));
            tab.setIndicator(indicator);
            tab.setContent(tag -> {
                return new View(MainActivity.this);
            });

            mTabHost.addTab(tab, mainTab.getClz(), null);

        }
    }

    @Override
    public void onTabChanged(String tabId) {
        final int size = mTabHost.getTabWidget().getTabCount();
        for (int i = 0; i < size; i++) {
            View v = mTabHost.getTabWidget().getChildAt(i);
            if (i == mTabHost.getCurrentTab()) {
                v.findViewById(R.id.tab_icon).setSelected(true);
                v.findViewById(R.id.tab_titile).setSelected(true);
                changeActionBarTitle(i);

            } else {
                v.findViewById(R.id.tab_icon).setSelected(false);
                v.findViewById(R.id.tab_titile).setSelected(false);
            }

        }


        supportInvalidateOptionsMenu();
    }

    private void changeActionBarTitle(int i) {
        if (i == 0) {
            if (mErrorLayout != null) mErrorLayout.setVisibility(View.GONE);
            mActionTitleView.setText("亲测");
            mIvArrow.setVisibility(View.GONE);
            mActionTitleView.setClickable(false);
        } else if (i == 1) {
            if (mErrorLayout != null) mErrorLayout.setVisibility(View.VISIBLE);
            mActionTitleView.setText("活动");
            mIvArrow.setVisibility(View.VISIBLE);
            mActionTitleView.setClickable(true);
        } else if (i == 2) {
            if (mErrorLayout != null) mErrorLayout.setVisibility(View.GONE);
            mActionTitleView.setText("邀请");
            mIvArrow.setVisibility(View.GONE);
            mActionTitleView.setClickable(false);
        } else if (i == 3) {
            mIvArrow.setVisibility(View.GONE);
            mActionTitleView.setClickable(false);
            if (mErrorLayout != null) mErrorLayout.setVisibility(View.GONE);
            if (TextUtils.isEmpty(UserName)) {
                mActionTitleView.setText("");
            } else {
                mActionTitleView.setText(UserName);
            }
        }
    }


    @Override
    public void onBackPressed() {

        if (System.currentTimeMillis() - mLastExitTime < 2000) {
            super.onBackPressed();
        } else {
            mLastExitTime = System.currentTimeMillis();
            AppContext.showToastShort(R.string.tip_click_back_again_to_exist);
        }
    }

    @Override
    public SlidingTabLayout getSlidingTabLayout() {
//        return mSlidingTabLayout;
        return null;
    }

    @Override
    public int getCurrentTab() {
        return mTabHost.getCurrentTab();
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
    }

    @Override
    public void onDownMotionEvent() {
    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
        if (!mScrolled) {
            // This event can be used only when TouchInterceptionFrameLayout
            // doesn't handle the consecutive events.
            adjustToolbar(scrollState);
        }
    }

    private Scrollable getCurrentScrollable() {
        Fragment fragment = getCurrentFragment();
        if (fragment == null) {
            return null;
        }
        View view = fragment.getView();
        if (view == null) {
            return null;
        }
        return (Scrollable) view.findViewById(R.id.recycleView);
    }

    private MySwipeRefreshLayout getCurrentRefreshLayout() {
        Fragment fragment = getCurrentFragment();
        if (fragment == null) {
            return null;
        }
        View view = fragment.getView();
        if (view == null) {
            return null;
        }
        return (MySwipeRefreshLayout) view.findViewById(R.id.srl_refresh);
    }

    private void adjustToolbar(ScrollState scrollState) {
        int toolbarHeight = mToolbarView.getHeight();
        final Scrollable scrollable = getCurrentScrollable();
        if (scrollable == null) {
            return;
        }
        int scrollY = scrollable.getCurrentScrollY();
        if (scrollState == ScrollState.DOWN) {
            showToolbar();
        } else if (scrollState == ScrollState.UP) {
            if (toolbarHeight <= scrollY) {
                hideToolbar();
            } else {
                showToolbar();
            }
        } else if (!toolbarIsShown() && !toolbarIsHidden()) {
            // Toolbar is moving but doesn't know which to move:
            // you can change this to hideToolbar()
            showToolbar();
        }
    }

    private Fragment getCurrentFragment() {
        Fragment fragment = getPagerFragment();
        if (fragment != null && fragment instanceof IPagerFragment) {
            IPagerFragment fc = (IPagerFragment) fragment;

            fragment = fc.getCurrentFragment();
            return fragment;
        }
        return null;
    }

    private Fragment getPagerFragment() {
        return getSupportFragmentManager().findFragmentByTag(mTabHost.getCurrentTabTag());
    }

    private boolean toolbarIsShown() {
        return ViewHelper.getTranslationY(mInterceptionLayout) == 0;
    }

    private boolean toolbarIsHidden() {
        return ViewHelper.getTranslationY(mInterceptionLayout) == -mToolbarView.getHeight();
    }

    private boolean mToolbarShow = true;

    private void showToolbar() {
        mToolbarShow = true;
        animateToolbar(0);
    }

    private void hideToolbar() {
        mToolbarShow = false;
        animateToolbar(-mToolbarView.getHeight());
    }

    private void animateToolbar(final float toY) {
        float layoutTranslationY = ViewHelper.getTranslationY(mInterceptionLayout);
        if (layoutTranslationY != toY) {
            ValueAnimator animator = ValueAnimator.ofFloat(ViewHelper.getTranslationY(mInterceptionLayout), toY).setDuration(200);
            animator.addUpdateListener(animation -> {
                float translationY = (float) animation.getAnimatedValue();
                ViewHelper.setTranslationY(mInterceptionLayout, translationY);
                if (translationY < 0) {
                    FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mInterceptionLayout.getLayoutParams();
                    lp.height = (int) (-translationY + getScreenHeight());
                    mInterceptionLayout.requestLayout();
                }
            });
            animator.start();
        }
    }


    @Override
    public void onAccountSelected(MediaAccount mediaAccount) {
        if (mSelectPopup != null) mSelectPopup.dismiss();
        notifyAccountSelected(mediaAccount);

    }


    private void notifyAccountSelected(MediaAccount mediaAccount) {
        mActionTitleView.setText(mediaAccount.getName());
        EventBus.getDefault().post(new MediaChangeEvent(MediaChangeEvent.EVENT_MEDIA_SELECT, mediaAccount));
    }


    private Observable<Result<List<MediaAccount>>> loadMediaAccountFromDB(int platform) {
        Observable<Result<List<MediaAccount>>> observable = Observable.create(new Observable.OnSubscribe<Result<List<MediaAccount>>>() {

            @Override
            public void call(Subscriber<? super Result<List<MediaAccount>>> subscriber) {
                if (mediaAccountDAO == null) {
                    mediaAccountDAO = DAOFactory.getMediaAccountDAO();
                }
                if (System.currentTimeMillis() - last_media_account_update > AppConstant.MEDIA_UPDATE_INTERVAL_TIME) {
                    last_media_account_update = System.currentTimeMillis();

                    List<MediaAccount> mediaAccounts = mediaAccountDAO.find(platform);
                    Result<List<MediaAccount>> result = new Result<>();
                    if (mediaAccounts != null && mediaAccounts.size() != 0) {
                        result.setData(mediaAccounts);
                        subscriber.onNext(result);

                    } else {
                        subscriber.onCompleted();
                    }

                } else {
                    mediaAccountDAO.removeAll();
                    subscriber.onCompleted();
                }


            }
        });

        mediaAccountDAO.close();
        return observable;

    }


    private Observable<Result<List<MediaAccount>>> loadMediaAccountFromNet(int platform) {
        return ApiFactory.getUserApi().getMediaAccountList(platform);
    }

    private void loadMediaAccountList(int platform) {
        loadMediaAccountFromNet(platform)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<List<MediaAccount>>>() {

                    @Override
                    public void onCompleted() {
//                        loadMediaAccountSuccess();
                    }

                    @Override
                    public void onNext(Result<List<MediaAccount>> listResult) {
                        List<MediaAccount> data = listResult.getData();
                        if (data != null && !data.isEmpty()) {
                            AppContext.setMeidaAccount(true);
                            convertData(data);
                        }else{
                            AppContext.setMeidaAccount(false);
                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        AppContext.showToastShort(e.getMessage());

                    }
                });


    }

    private void convertData(List<MediaAccount> data) {
        HashMap<Integer, MediaChannel> map = new HashMap<>();
        for (MediaAccount item : data) {
            if (item.getStatus() != MediaAccount.STATE_ACTIVE) continue;
            if (!map.containsKey(item.getPlatform())) {
                MediaChannel channel = new MediaChannel();
                channel.setPlatform(item.getPlatform());
                MediaAccountList accounList = channel.getAccounList();
                accounList.getAccountList().add(item);
                map.put(item.getPlatform(), channel);
            } else {
                MediaChannel channel = map.get(item.getPlatform());
                List<MediaAccount> accountList = channel.getAccounList().getAccountList();
                accountList.add(item);
            }
        }

        mediaChannelList.getChannelList().clear();

        for (Map.Entry<Integer, MediaChannel> entry : map.entrySet()) {
            mediaChannelList.getChannelList().add(entry.getValue());
        }
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }


    public void hideNoMediaAccountEmptyLayout() {
        if (mErrorLayout != null) {
            mErrorLayout.setVisibility(View.GONE);
            int count = mPagerWrapper.getChildCount();
            for (int i = 0; i < count; i++) {
                mPagerWrapper.removeView(mErrorLayout);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTabHostChanged(ActiveTabHostEvent event) {

        LogUtils.printLogE("ActiveTabHostEvent :" + event.getId());
        if (event.getType() == ActiveTabHostEvent.NORAML) {
            mTabHost.setCurrentTab(1);
            Intent intent = new Intent(AppConstant.INTENT_ACTION_TAB_JUMP);
            intent.putExtra("tabid", event.getId());
            sendBroadcast(intent);
        } else if (event.getType() == ActiveTabHostEvent.CAMPAING) {
            mTabHost.setCurrentTab(0);
            notifyTabChange(event.getId());
            Intent intent = new Intent(AppConstant.INTENT_ACTION_CAMPAIGN_TAB_JUMP);
            intent.putExtra("tabid", event.getId());
            sendBroadcast(intent);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserChange(UserChangeEvent userNameChange) {
        UserName = userNameChange.getName();
        if (UserName != null)
            mActionTitleView.setText(UserName);

        EventBus.getDefault().post(new CampaignStatueRefreshEvent(0));
        EventBus.getDefault().post(new ActiveStatueRefreshEvent(0));

    }

    private void notifyTabChange(int tabId) {
        LogUtils.printLogD("notifyTabChange " + tabId);
        Intent intent = new Intent(AppConstant.INTENT_ACTION_TAB_JUMP);
        intent.putExtra("tabid", tabId);
        sendBroadcast(intent);
    }

}
